<template>
  <div>
    <div class="square">
      <div class="list" :class="dynamicClass" v-for="(obj,index) in wrapper" :key="index">
        <div :id="'wrapper'+index"><div :id="'box'+index"></div></div>
        <span @click="closeStream(index)">{{getText(index)}}</span>
      </div>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import _ from 'lodash';
import RtmpPlayer from "../components/RtmpPlayer.vue";
import util from "../util/util";
import store from '../store/index';
export default {
  name: "square",
  components: {
    RtmpPlayer
  },
  data() {
    return {
      dynamicClass: "",
      wrapper: [],
      texts: [],
      urls: [],
      tmpUrls: [],
      screenWidth: window.screen.width,
      classes:["one","four","nine","sixteen"],
      resizeTimer: null
    };
  },
  props: {
    index: {
      type: Number,
      default: 1
    },
    streamUrl: {
      type: String,
      default: ""
    },
    text: {
      type: String,
      default: ""
    }
  },
  computed: {
    getCollapse() {
      return this.$store.state.collapseFlag;
    },
    _windowResize() {
      return _.throttle(() => {
        this.windowResize();
      }, 400);
    }
  },
  created() {
    let number = this.getNumber(this.index);
    this.dynamicClass = this.getClass(this.index);
    this.initWrapper(number);
  },
  mounted() {
    if (this.streamUrl) {
      this.play(this.streamUrl);
    }
    window.addEventListener("resize",this._windowResize);
  },
  beforeDestroy() {
    for (let i = 0; i < this.wrapper.length; i++) {
      if (this.wrapper[i]) this.wrapper[i].destroy = true;  //this.$destroy('componentName')?
    }
  },
  destroyed(){
    window.removeEventListener("resize",this._windowResize);
  },
  watch: {
    index(newVal,oldVal) {
      let newNum = this.getNumber(newVal);
      let oldNum = this.getNumber(oldVal);
      this.tmpUrls = this.getUrlsByOldUrls(newNum,oldNum);
      this.destroyWrapper();
      this.dynamicClass = this.getClass(newVal);
      this.initWrapper(newNum);
      for (let i=0; i<this.tmpUrls.length; i++) {
        if(this.tmpUrls[i]) this.play(this.tmpUrls[i]);
      }
    },
    streamUrl(val) {
      if (this.index == 1) {
        this.closeStream(0);
      }
      if (val) {
        this.play(val);
      }
    },
    getCollapse(){
      this.handleCollapse();
    }
  },
  methods: {
    getClass(screenIndex) {
      return this.classes[screenIndex-1] || "";
    },
    getNumber(screenIndex) {
      let number = 1;
      switch (screenIndex) {
        case 1:
          number = 1;
          break;
        case 2:
          number = 4;
          break;
        case 3:
          number = 9;
          break;
        case 4:number = 16;break;
      }
      return number;
    },
    initWrapper(number) {
      for (let i = 0; i < number; i++) {
        this.wrapper.push(null);
        this.urls.push("");
        this.texts.push("");
      }
    },
    destroyWrapper() {
      for (let i = 0; i < this.wrapper.length; i++) {
        this.closeStream(i);
      }
      this.wrapper = [];
      this.texts = [];
      this.urls = [];
    },
    createWrapper(index) {
      const Player = Vue.extend(RtmpPlayer);  //返回一个vue实例
      let instance = new Player();
      instance.$mount("#box" + index);  //会替换掉id为 box+index 的div
      return instance;
    },
    getWrapperIndex() {
      let i, index;
      for (i = 0; i < this.wrapper.length; i++) {
        if (!this.wrapper[i]) {
          index = i;
          break;
        }
      }
      if (i >= this.wrapper.length) {
        index = -1;
      }
      return index;
    },
    getUrlsByOldUrls(newNum,oldNum){
      let _urls = [];
      if(newNum < oldNum){
        _urls = this.getUrlsByTopNumber(newNum);
      }else{
        _urls = JSON.parse(JSON.stringify(this.urls));
      }
      //添加用户在导航栏中选中的url
      if(this.streamUrl && _urls.length>0 && _urls.indexOf(this.streamUrl)==-1){
        if(_urls.length >= newNum){
          _urls[_urls.length-1] = this.streamUrl;
        }else{
          _urls.push(this.streamUrl);
        }
      }
      return _urls;
    },
    getUrlsByTopNumber(num){
      let _urls = [];
      let tmpUrls = JSON.parse(JSON.stringify(this.urls));
      for(let i=0; i<tmpUrls.length; i++){
        if(num <= 0) break;
        if(tmpUrls[i]){
          _urls.push(tmpUrls[i]);
          num--;
        }
      }
      return _urls;
    },
    setText(index, text) {
      this.$set(this.texts, index, text); //使用set函数 vue才能监听到变化
    },
    getText(index) {
      return this.texts[index] ? "关闭视频流" : "暂无视频流";
    },
    setUrl(index, url) {
      this.$set(this.urls, index, url);
    },
    getUrl(index) {
      return this.urls[index];
    },
    play(url) {
      console.log(url);
      if (!util.hasFlash()) {
        this.$message({
          type: "error",
          message: "你的浏览器未允许使用Flash插件，将无法播放视频流"
        });
        return false;
      }
      //是否有对应的url视频流已经播放
      if(this.urls.indexOf(url)!=-1){
        this.$message({
          type: "info",
          message: "该视频流正在播放中"
        });
        return false;
      }
      let wrapperIndex = this.getWrapperIndex();
      if (this.index == 1) {
        wrapperIndex = 0;
      }
      if (wrapperIndex == -1) return false;
      try {
        this.wrapper[wrapperIndex] = this.createWrapper(wrapperIndex);
        this.wrapper[wrapperIndex].playerOptions.aspectRatio = this.getAspectRatio();
        this.wrapper[wrapperIndex].playerOptions.sources[0].src = url;
        this.wrapper[wrapperIndex].reLoad = !this.wrapper[wrapperIndex].reLoad;
        this.setText(wrapperIndex, url);
        this.setUrl(wrapperIndex, url);
      } catch (error) {
        console.log(error);
        this.setText(wrapperIndex, "");
        return false;
      }
    },
    closeStream(index) {
      if (this.wrapper[index]) {
        this.wrapper[index].destroy = true;
        document.getElementById("wrapper" + index).innerHTML = "";
        this.wrapper[index] = null;
        this.setText(index, "");
        this.setUrl(index, "");
        this.createElement(index);
      }
    },
    createElement(index) {
      //为防止重新挂载时 id为box+index 的div已被替换
      let id = "box" + index;
      let oDiv = document.createElement("div");
      oDiv.setAttribute("id", id);
      let parent = document.getElementById("wrapper" + index);
      parent.appendChild(oDiv);
    },
    getAspectRatio() {
      let height = document.getElementById("wrapper0").clientHeight;
      let width = document.getElementById("wrapper0").clientWidth;
      return `${width}:${height}`;
    },
    handleCollapse() {
      if(this.resizeTimer) clearTimeout(this.resizeTimer); //防止resize执行两次
      this.resizeTimer = setTimeout(()=>{
        this.resizeVideo();
      },400);
    },
    windowResize() {
      this.isFullScreen() || this.resizeVideo();
    },
    resizeVideo(){
      for (let index = 0; index < this.wrapper.length; index++) {
        if (this.wrapper[index]) {
          this.wrapper[index].playerOptions.aspectRatio = this.getAspectRatio();
          // this.wrapper[index].reLoad = !this.wrapper[index].reLoad;
        }
      }
    },
    isFullScreen() {
      return  !!(
          document.fullscreen || 
          document.mozFullScreen ||                         
          document.webkitIsFullScreen ||       
          document.webkitFullScreen || 
          document.msFullScreen 
      );
    }
  }
};
</script>
<style lang="scss" scoped>
@import "../assets/basic.scss";
.square {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}

.list {
  float: left;
  height: 100%;
  width: 100%;
  position: relative;
}
.list > div {
  position: absolute;
  left: 2px;
  right: 2px;
  top: 2px;
  bottom: 2px;
  border-radius: 2px;
  //background-color: #eee;
  background:$ims-videobox-color;
  z-index: 1;
}
.list > span {
  display: inline-block;
  position: absolute;
  right: 2px;
  top: 2px;
  /* border-radius: 2px; */
  padding: 5px 10px;
  text-align: center;
  z-index: 2;
  background: #00BAE0;
  color: #fff;
  &:hover {
    cursor: pointer;
    background: #fff;
    color: #409eff;
  }
}

/* .list:after {
  content: "暂无视频";
  position: absolute;
  height: 30px;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  text-align: center;
  font: 24px/30px bold 'microsoft yahei';
} */
.one {
  width: 100%;
  height: 100%;
}
.four {
  width: 50%;
  height: 50%;
}
.nine {
  width: 33.3%;
  height: 33.3%;
}
.sixteen {
  width: 25%;
  height: 25%;
}
</style>